package com.czk.gulimall.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/3/7 22:26
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token") String token) {
        String username = stringRedisTemplate.opsForValue().get(token);
        return username;
    }

    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String url, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 将用户存到redis
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            stringRedisTemplate.opsForValue().set(uuid, username);
            // 设置cookie
            // 浏览器以后访问这个域名都要带上这个cookie
            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
            // 登陆成功
            return "redirect:" + url + "?token=" + uuid;
        }
        return "";
    }

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String url, Model model,
                        @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            // 登陆过，留下了痕迹
            // 跳回，直接返回
            return "redirect:" + url + "?token" + sso_token;
        }
        model.addAttribute("url", url);
        return "login";
    }
}
